package controllers

import (
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/cache"
	"news/models"
)

type NewController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func NewList() {
	news := []models.News{}
	models.DB.Find(&news)
	List, _ := json.Marshal(&news)
	Key := "news"
	cache.Rdb.Set(context.Background(), Key, List, 0)
}

func (c *NewController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	status := c.GetString("status")
	news := models.News{
		Title:  title,
		Time:   time,
		Status: status,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: news,
		}
		c.ServeJSON()
	}
	NewList()
}

func (c *NewController) List() {

	var news []models.News
	err := models.DB.Find(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: news,
		}
		c.ServeJSON()
	}
}

func (c *NewController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	status := c.GetString("status")
	news := models.News{
		Title:  title,
		Time:   time,
		Status: status,
	}
	err := models.DB.Where("ID", id).Save(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: news,
		}
		c.ServeJSON()
	}
	NewList()
}

func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("id=?", id).Delete(&models.News{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
	NewList()
}
